package cn.fengso.job;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

import cn.fengso.config.Config;
import cn.fengso.service.impl.MessageHandlerServiceImpl;
import cn.fengso.vo.Status;

public class CountJob implements Job {

	private static final int PAUSE = 0;
	private static final int RUNNING = 1; 
	private static Map<String, Status> stateMap = new HashMap<String, Status>();

	public void execute(JobExecutionContext arg0) throws JobExecutionException {
		Map<String, Integer> countMap = MessageHandlerServiceImpl.countMap; 
		Iterator<String> ite = countMap.keySet().iterator();
		while (ite.hasNext()) {
			String key = ite.next(); 
			if (stateMap.containsKey(key)) {
				Status st = stateMap.get(key);
				if (st.getState() == PAUSE) {
					countMap.put(key, 0);
					if (st.getStopTime() + st.getIntval() < System
							.currentTimeMillis()) {
						st.setState(RUNNING);
					} else {
						continue;
					}
				}
			}
			int count = countMap.get(key);
			if (count > Config.getInteger("MAX_COUNT")) {
				stateMap.put(key, new Status(System.currentTimeMillis(),
						Config.getInteger("PAUSE_TIME"), PAUSE)); 
				sendMessage(key);
			} 
			countMap.put(key, 0);
		}

	}

	private void sendMessage(final String key) {
		new Thread(new Runnable(){

			public void run() {
				System.out.println(key+"地震啦！@！"); 
			}}).start();
	}

}
